package com.ybb.vue.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ybb.vue.common.R;
import com.ybb.vue.common.Result;
import com.ybb.vue.common.util.OperationRecordsUtils;
import com.ybb.vue.entity.SysRole;
import com.ybb.vue.entity.SysRoleMenu;
import com.ybb.vue.entity.SysUserRole;
import com.ybb.vue.service.SysRoleMenuService;
import com.ybb.vue.service.SysRoleService;
import com.ybb.vue.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统角色Controller控制器
 * @author ybb
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 查询所有的角色
     * @return
     */
    @GetMapping("/listAll")
    @PreAuthorize("hasAuthority('system:role:query')")
    public R listAll(){
        Map<String,Object> resultMap=new HashMap<>();
        List<SysRole> roleList = sysRoleService.list();
        resultMap.put("roleList",roleList);
        return R.ok(resultMap);
    }

    /**
     * 查询role列表
     * @param pageNum
     * @param pageSize
     * @param search
     * @return
     */
    @GetMapping("/roleList")
    @PreAuthorize("hasAuthority('system:role:list')"+"||"+"hasAuthority('system:role:query')")
    public Result<?> userList (@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               @RequestParam(defaultValue = "") String search) {
        Page<SysRole> result = sysRoleService.page(new Page<>(pageNum, pageSize), Wrappers.<SysRole>lambdaQuery().like(SysRole::getName, search));
        return Result.success(result);
    }

    /**
     * 添加或者修改
     * @param sysRole
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:role:add')"+"||"+"hasAuthority('system:role:edit')")
    public R save(@RequestBody @Valid SysRole sysRole){
        if(sysRole.getId()==null || sysRole.getId().equals("-1")){
            sysRoleService.save(sysRole);

            // 操作记录
            String content = "操作了角色表，【新增】了1条记录，记录id为：" + sysRole.getId();
            OperationRecordsUtils.createOperationRecords(content);
        }else{
            sysRoleService.updateById(sysRole);

            // 操作记录
            String content = "操作了角色表，【修改】了1条记录，记录id为：" + sysRole.getId();
            OperationRecordsUtils.createOperationRecords(content);
        }
        return R.ok();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:role:query')")
    public R findById(@PathVariable(value = "id")String id){
        SysRole sysRole = sysRoleService.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("sysRole",sysRole);
        return R.ok(map);
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:role:delete')")
    public R delete(@RequestBody String[] ids){
        sysRoleService.removeByIds(Arrays.asList(ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("role_id",ids));

        // 操作记录
        String content = "操作了角色表，【删除】了"+Arrays.asList(ids).size()+"条记录，记录id为：" + ids;
        OperationRecordsUtils.createOperationRecords(content);
        return R.ok();
    }

    /**
     * 获取当前角色的权限菜单ID集合
     * @param id
     * @return
     */
    @GetMapping("/menus/{id}")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public R menus(@PathVariable(value = "id")Long id){
        List<SysRoleMenu> roleMenuList = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", id));
        List<Long> menuIdList = roleMenuList.stream().map(p -> p.getMenuId()).collect(Collectors.toList());
        return R.ok().put("menuIdList",menuIdList);
    }

    /**
     * 更新角色权限信息
     * @param id
     * @param menuIds
     * @return
     */
    @Transactional
    @PostMapping("/updateMenus/{id}")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public R updateMenus(@PathVariable(value = "id")Long id, @RequestBody Long[] menuIds){
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id",id));
        List<SysRoleMenu> sysRoleMenuList=new ArrayList<>();
        Arrays.stream(menuIds).forEach(menuId->{
            SysRoleMenu roleMenu=new SysRoleMenu();
            roleMenu.setRoleId(id);
            roleMenu.setMenuId(menuId);
            sysRoleMenuList.add(roleMenu);
        });
        sysRoleMenuService.saveBatch(sysRoleMenuList);

        // 操作记录
        String content = "操作了角色表，【更改角色权限】，记录id为：" + id;
        OperationRecordsUtils.createOperationRecords(content);
        return R.ok();
    }
}